<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Proitem extends Auth
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    // 配件
    public function list(Request $request)
    {   
        if(isset($this->data['request']) && $this->data['request'] == 'vue'){
            $returnData['item_cat'] = getSearch('pro_item_type','zu',['zu.*,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
            foreach ($returnData['item_cat'] as $k => $v) {
                if($v['is_public'] ==1){
                    $pro_name = getValue('multi_lang',['mkey'=>'pro_'.$v['pro_id'],'lang'=>$this->lang],'content');
                    $prochar_model = getValue('prochar',['id'=>$v['prochar_id']],'model');
                    $returnData['item_cat'][$k]['pro'] = $pro_name.' / '.$prochar_model;
                }else{
                    $returnData['item_cat'][$k]['pro'] = '';
                }
                $returnData['item_cat'][$k]['is_status'] = lang(getViewMultiLanguage($v['status']));
                $returnData['item_cat'][$k]['is_public_note'] = $v['is_public'] == 1 ? 'o' : '-';
                $returnData['item_cat'][$k]['is_hide_note'] = $v['is_hide'] == 1 ? 'o' : '-';
            }
            
            $returnData['size'] = count( $returnData['item_cat']);
            // 获取分页数据
            if(isset($this->data['page']) && isset($this->data['limit'])){
                $returnData['item_cat'] = array_slice($returnData['item_cat'],$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                $returnData['page'] = $this->data['page'];
            }else{
                $returnData['page'] =1;
            }

            // $returnData['item_cat'] = getMultiLangName('pro_item_type',['*'],'1=1','id asc');
            return json_encode($returnData);

        }else{
            return view('list',['request'=>'list']);
        }
        
    }

    public function addopen(){
        if(isset($this->data['request']) && $this->data['request'] == 'insert'){
            if($this->data['itemcat_name']['zh'] == ''){
                return json_encode(array('status'=>2,'msg'=>lang('missing_name')));
            }else{

                $has = hasData('multi_lang',['lang'=>$this->lang,'content'=>$this->data['itemcat_name']['zh'],'mkey'=>['like','%pro_item_type_%']]);
                if($has){
                    return json_encode(array('status'=>3,'msg'=>' '.lang('already_exists')));
                }
                if($this->data['is_public'] == 'false'){
                    $insertitem['is_public'] = 2;
                }else{
                    if(isset($this->data['pro_id']) && $this->data['pro_id'] && isset($this->data['prochar_id'])&& $this->data['prochar_id']){
                        $insertitem['is_public'] = 1;
                        $insertitem['pro_id'] = $this->data['pro_id'];
                        $insertitem['prochar_id'] = $this->data['prochar_id'];
                    }else{
                        return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
                    }
                    
                }

                Db::startTrans();
                    $res = insertData('pro_item_type',$insertitem);
                    if($res){
                        $res1 = updateData('pro_item_type',['id'=>$res],['mkey'=>'pro_item_type_'.$res]);
                        // foreach ($this->data['itemcat_name'] as $k => $v) {

                        $lang_cate = getLanguage();
                        foreach ($lang_cate as $k => $v) {
                            $res2 = insertData('multi_lang',['mkey'=>'pro_item_type_'.$res,'lang'=>$v['code'],'content'=>$this->data['itemcat_name']['zh']]);
                        }
                        if($res1 && $res2){
                            Db::commit();
                            return json_encode(array('status'=>1,'msg'=>$this->data['itemcat_name']['zh'].' '.lang('added_successfully')));
                        }else{
                            Db::rollback();
                            return json_encode(array('status'=>0,'msg'=>$this->data['itemcat_name']['zh'].' '.lang('add_failed')));
                        }
                    }else{
                        Db::rollback();
                        return json_encode(array('status'=>0,'msg'=>$this->data['itemcat_name']['zh'].' '.lang('add_failed')));
                    }

            }
            
            // $insertItemcat = insertData('pro_item_type',['']);
        }else if(isset($this->data['request']) && $this->data['request'] == 'add'){
            // $procat = getSearch('procat','zu',['zu.*,mu.content'],['mu.lang'=>$this->lang],[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id desc');
            $procat = getMultiLangName('procat',['*'],['status'=>1],'drank asc');
            $procat = getTree($procat);
            // return $procat;
            return view('itemopen',['title'=>lang('add_accessory_type'),'request'=>'add','procat'=>$procat]);
        }else{
            return $this->proAddNewJump_itemAjax($this->data,$this->lang);
        }
    }

    //产品配件AJAX
    // public function proAddNewJump_itemAjax(){
    //     if($this->data['request'] == 'pro'){
    //         $pro2cate = getDatas('pro2cate',['*'],['procat_id'=>$this->data['cat_id']]);
    //         if(!empty($pro2cate)){
    //             $prolist = [];
    //             foreach ($pro2cate as $k => $v) {
    //                 if(isset($this->data['pro_id']) && $v['pro_id'] != $this->data['pro_id']){
    //                     $result = getMultiLangName('pro',['*'],['id'=>$v['pro_id'],'is_public'=>1],'id asc');
    //                     if(!empty($result)) $prolist[] = $result;
                        
    //                 }
    //                 else{
    //                     $result = getMultiLangName('pro',['*'],['id'=>$v['pro_id'],'is_public'=>1],'id asc');
    //                     if(!empty($result)) $prolist[] = $result;
    //                 }
    //             }
    //             return json_encode(array('status'=>1,'msg'=>'OK','data'=>$prolist));
    //         }
    //     }elseif ($this->data['request'] == 'prochar') {
    //         $prochar = getDatas('prochar',['*'],['pro_id'=>$this->data['id']]);
    //         if(!empty($prochar)){
    //             foreach ($prochar as $k => $v) {
    //                 $returnFeature[$k]['id'] =  $v['id'];
    //                 $returnFeature[$k]['content_zh'] = '型号'.$v['model'].'/';
    //                 $returnFeature[$k]['content_en'] = '型号'.$v['model'].'/';
    //                 $returnFeature[$k]['content_pt'] = '型号'.$v['model'].'/';
    //                 $prochar2feature = getDatas('profeature2char',['*'],['prochar_id'=>$v['id']]);
    //                 if(!empty($prochar2feature)){
    //                     foreach ($prochar2feature as $k1 => $v1) {
    //                         $feature = getMultiLangName('proattr_value',['*'],['id'=>$v1['profeature_value_id']],'id asc')[0];
    //                         $returnFeature[$k]['content_zh'] .= $feature['name_zh'].'/';
    //                         $returnFeature[$k]['content_en'] .= $feature['name_en'].'/';
    //                         $returnFeature[$k]['content_pt'] .= $feature['name_pt'].'/';
    //                     }
    //                 }
    //                 rtrim($returnFeature[$k]['content_zh'],'/');
    //                 rtrim($returnFeature[$k]['content_en'],'/');
    //                 rtrim($returnFeature[$k]['content_pt'],'/');
    //             }
    //         }else{
    //             $returnFeature=[];
    //         }
    //         return json_encode(array('status'=>1,'msg'=>'OK','data'=>$returnFeature));

    //     }else if($this->data['request'] == 'search'){
    //         // return $this->data;
    //         if(isset($this->data['searchText']) && $this->data['searchText']){
    //             $join  = [['multi_lang mu','zu.mkey = mu.mkey']];
    //             $field = ['zu.*,mu.content'];
    //             $where['mu.lang'] = $this->lang;
    //             if(isset($this->data['pro_id'])){
    //                 $where['zu.id'] = ['!=',$this->data['pro_id']];
    //             }
                
    //             // 查找
    //             $where['zu.id|mu.content'] = ['like',"%".$this->data['searchText'].'%'];   
    //             $productList = getSearch('pro','zu',$field,$where,$join,'zu.id desc');
    //             foreach ($productList as $k => $v) {
    //                 // $productList[$k]['name_'.$v['lang']] = getValue('multi_lang',['mkey'=>'pro_'.$v['id'],'lang'=>$v['lang']],'content');
    //                 $pro_multi = getDatas('multi_lang',['*'],['mkey'=>'pro_'.$v['id']]);
    //                 foreach ($pro_multi as $k1 => $v1) {
    //                     $productList[$k]['name_'.$v1['lang']] = $v1['content'];
    //                 }
    //             }
    //             // return $productList;
    //             return json_encode(array('status'=>1,'msg'=>'OK','data'=>$productList));

    //         }else{
    //             return array();
    //         }
    //     }
    // }
    public function proAddNewJump_itemAjax($data,$lang){
        if($data['request'] == 'pro'){
            $pro2cate = getDatas('pro2cate',['*'],['procat_id'=>$data['cat_id']]);
            if(!empty($pro2cate)){
                $prolist = [];
                foreach ($pro2cate as $k => $v) {
                    if(isset($data['pro_id']) && $v['pro_id'] != $data['pro_id']){
                        $result = getMultiLangName('pro',['*'],['id'=>$v['pro_id']],'id asc');
                        if(!empty($result)) $prolist[] = $result[0];
                        
                    }
                    else{
                        $result = getMultiLangName('pro',['*'],['id'=>$v['pro_id']],'id asc');
                        if(!empty($result)) $prolist[] = $result[0];
                    }
                }
                return json_encode(array('status'=>1,'msg'=>'OK','data'=>$prolist));
            }
        }elseif ($data['request'] == 'prochar') {
            $prochar = getDatas('prochar',['*'],['pro_id'=>$data['id']]);
            if(!empty($prochar)){
                foreach ($prochar as $k => $v) {
                    $returnFeature[$k]['id'] =  $v['id'];
                    $returnFeature[$k]['content_zh'] = '型号'.$v['model'].'/';
                    $returnFeature[$k]['content_en'] = '型号'.$v['model'].'/';
                    $returnFeature[$k]['content_pt'] = '型号'.$v['model'].'/';
                    $prochar2feature = getDatas('profeature2char',['*'],['prochar_id'=>$v['id']]);
                    if(!empty($prochar2feature)){
                        foreach ($prochar2feature as $k1 => $v1) {
                            $feature = getMultiLangName('proattr_value',['*'],['id'=>$v1['profeature_value_id']],'id asc')[0];
                            $returnFeature[$k]['content_zh'] .= $feature['name_zh'].'/';
                            $returnFeature[$k]['content_en'] .= $feature['name_en'].'/';
                            $returnFeature[$k]['content_pt'] .= $feature['name_pt'].'/';
                        }
                    }
                    rtrim($returnFeature[$k]['content_zh'],'/');
                    rtrim($returnFeature[$k]['content_en'],'/');
                    rtrim($returnFeature[$k]['content_pt'],'/');
                }
            }else{
                $returnFeature=[];
            }
            return json_encode(array('status'=>1,'msg'=>'OK','data'=>$returnFeature));

        }else if($data['request'] == 'searchText'){
            // return $this->data;
            if(isset($data['searchText']) && $data['searchText']){
                $join  = [['multi_lang mu','zu.mkey = mu.mkey']];
                $field = ['zu.*,mu.content'];
                $where['mu.lang'] = $lang;
                if(isset($data['pro_id'])){
                    $where['zu.id'] = ['not in',$data['pro_id']];
                }
                
                // 查找
                $where['zu.id|mu.content'] = ['like',"%".$data['searchText'].'%'];  
                $where['zu.is_item'] = 0;
                // $where['zu.is_public'] = 1;
                $productList = getSearch('pro','zu',$field,$where,$join,'zu.id desc');
                if(!empty($productList)){
                    foreach ($productList as $k => $v) {
                        // $productList[$k]['name_'.$v['lang']] = getValue('multi_lang',['mkey'=>'pro_'.$v['id'],'lang'=>$v['lang']],'content');
                        $pro_multi = getDatas('multi_lang',['*'],['mkey'=>'pro_'.$v['id']]);
                        foreach ($pro_multi as $k1 => $v1) {
                            $productList[$k]['name_'.$v1['lang']] = $v1['content'];
                        }
                    }
                    return json_encode(array('status'=>1,'msg'=>'OK','data'=>$productList));
                }else{
                    return json_encode(array('status'=>3,'msg'=>lang('no_data')));
                }
            }else{
                return json_encode(array('status'=>3,'msg'=>lang('no_data')));
            }
        }
    }


    public function editopen(){
        if(isset($this->data['request']) && $this->data['request'] == 'update'){
            // return $this->data;
            if($this->data['itemcat_name']['zh'] == ''){
                return json_encode(array('status'=>2,'msg'=>lang('missing_name')));
            }else{
                if($this->data['is_public'] == 'false'){
                    $insertitem['is_public'] = 2;
                }else{
                    if(isset($this->data['pro_id']) && $this->data['pro_id'] && isset($this->data['prochar_id']) &&$this->data['prochar_id']){
                        $insertitem['is_public'] = 1;
                    }else{
                        return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
                    }
                }
                Db::startTrans();
                    $insertitem['pro_id'] = $this->data['pro_id'];
                    $insertitem['prochar_id'] = $this->data['prochar_id'];
                    $res = updateData('pro_item_type',['id'=>$this->data['id']],$insertitem);
                    foreach ($this->data['itemcat_name'] as $k => $v) {
                        $res2 = updateData('multi_lang',['mkey'=>'pro_item_type_'.$this->data['id'],'lang'=>$k],['content'=>$v]);
                        if($k == $this->lang) $content = $v;
                    }
                    if($res >= 0 && $res2 >= 0){
                        Db::commit();
                        return json_encode(array('status'=>1,'msg'=>$content.' '.lang('edited_successfully')));
                    }else{
                        Db::rollback();
                        return json_encode(array('status'=>0,'msg'=>$content.' '.lang('edit_failed')));
                    }
            }
        }else if(isset($this->data['request']) && $this->data['request'] == 'edit'){
            // 产品分类
            $procat = getMultiLangName('procat',['*'],['status'=>1],'drank asc');
            $procat = getTree($procat);
            // 产品

            // 配件类型
            $item = getMultiLangName('pro_item_type',['*'],['id'=>$this->data['id']],'id asc')[0];
            if($item['is_public'] == 1){
                $itempro = getMultiLangName('multi_lang',['*'],['mkey'=>'pro_'.$item['pro_id']],'id asc')[0];
                $itemprochar = getDatas('prochar',['id,model'],['id'=>$item['prochar_id']])[0];
                $itemprochar['content'] = lang('model').'_'.$itemprochar['model'];
                return view('itemopen',['title'=>lang('edit_accessory_type'),'request'=>'edit','procat'=>$procat,'itempro'=>$itempro,'itemprochar'=>$itemprochar,'item'=>$item]);
            }else{
                return view('itemopen',['title'=>lang('edit_accessory_type'),'id'=>$this->data['id'],'request'=>'edit','procat'=>$procat,'item'=>$item]);
            }
            
        }else {
            return $this->proAddNewJump_itemAjax($this->data,$this->lang);
        }
    }


            // 批量/单个删除
    public function batchDel()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->changeStatus($this->data,$this->lang);
        }
    }

    // 批量/单个隐藏
    public function batchHide()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->changeStatus($this->data,$this->lang);
        }
    }

    // 批量/单个恢复
    public function batchRestore()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->changeStatus($this->data,$this->lang);
        }
    }

    // 批量/单个清除
    public function batchClear()
    {
        if(!empty($this->data['id'])){  // 判断条件是否达成
            return $this->requestDel($this->data,$this->lang);
        }
    }


    public function changeStatus($data,$lang){
        if($data['id']){
            $res = updateData('pro_item_type',['id'=>$data['id']],['status'=>$data['status']]);
            $content = getValue('multi_lang',['mkey'=>'pro_item_type_'.$data['id'],'lang'=>$lang],'content');
            if($res){
                return json_encode(array('status'=>1,'msg'=>$content.' '.lang(getViewMultiLanguage($data['status'])).' '.lang('successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>$content.' '.lang(getViewMultiLanguage($data['status'])).' '.lang('failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
        }
    }

    public function requestDel($data,$lang){
        if($data['id']){
            $content = getValue('multi_lang',['mkey'=>'pro_item_type_'.$data['id'],'lang'=>$lang],'content');
            $res = deleteData('pro_item_type',['id'=>$data['id'],'status'=>2]);
            if($res){
                $res1 = deleteData('multi_lang',['mkey'=>'pro_item_type_'.$data['id']]);
                return json_encode(array('status'=>1,'msg'=>$content.' '.lang('cleared_successfully')));
            }else{
                return json_encode(array('status'=>0,'msg'=>$content.' '.lang('clear_failed')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>'improve_submission_data'));
        }
    }

}